<template>
    <div class="chat_div">
        <div style="padding: 0px; margin-bottom: 50px">
            <!-- 导航栏 -->
            <el-menu  default-active="/Chat" router class="el-menu-demo" mode="horizontal">
                <el-menu-item index="/"><i class="el-icon-s-home"></i></el-menu-item>
                <el-menu-item>目的地攻略</el-menu-item>
                <el-menu-item >游记</el-menu-item>
                <el-menu-item index="/Chat">问答</el-menu-item>
                <el-menu-item >当地向导</el-menu-item>
                <el-menu-item index="/MyHomePage">我的主页</el-menu-item>
            </el-menu>
            <el-row>
                <el-col :span="5" style="margin-top:60px;">
                    <el-card style="width: 330px; height: 640px; color: #333">
                        <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc" >{{this.tipText}}<span style="font-size: 12px"></span></div>
                        <div style="padding: 10px 0" v-for="user in users" :key="user.username">
                            <span>{{ user.username }}</span>
                            <i
                            class="el-icon-chat-dot-round"
                            style="margin-left: 10px; font-size: 16px; cursor: pointer"
                            @click="chatUserName(user.username)"></i>
                            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">chatting...</span>
                            <span style="margin-bottom:12px; font-size:12px; font-weight:bold; color:red;">{{user.unread}}</span>
                        </div>
                    </el-card>
                </el-col>
            <el-col :span="12" :push="1" style="margin-top:60px;">
                <div @mouseenter="liaotian" style="width: 900px;height:640px; margin: 0 auto; background-color: white;
                            border-radius: 5px; box-shadow: 0 0 10px #ccc;"  ref="main">
                <div style="text-align: center; line-height: 50px;">
                {{this.chatText}}{{this.chatUser}}
                </div>
                <div ref="box" style="height: 360px; overflow: auto;overflow-x: hidden; border-top: 1px solid #ccc" v-html="content"  ></div>
                <div style="height: 200px;width:900px;">
                    <el-tooltip   style="text-algin:left;margin-left:40px;" content="点击使用表情" placement="bottom" effect="light" :open-delay=1300 >
                        <el-button type="success" round size="mini" @click="abc">表情</el-button>
                    </el-tooltip>
                    <textarea id="emojiInput" v-model="text" style="height: 160px; width:896px; border: none; border-top: 1px solid #ccc;
                    border-bottom: 1px solid #ccc; outline: none"></textarea>
                    <picker style="height:200px;position: absolute;left: 10px;top:196px;" :autosize="{ minRows: 8, maxRows: 20 }" :include="['people','Smileys']" :showSearch="false" :showPreview="false" :showCategories="false" @select="addEmoji" v-show="this.expression"/>
                    <div style="text-align: right; padding-right: 10px">
                    <el-button type="primary" size="mini" @click="send">发送</el-button>
                    </div>
                </div>
                </div>
            </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>



let socket;
import { Picker } from "emoji-mart-vue"; //引入表情组件
const axios = require('axios')
export default {
    name: "Chat",
    components: { //注册组件，不能全局挂载
        Picker
    },
    data() {
        return {
            user: {},
            //显示在线用户
            users: [],
            //聊天对象
            chatUser: '',
            //存放聊天内容
            text: "",
            //存放未读消息
            ThatMessages:[],
            content: '',
            //获取当前用户登录名称
            userName:'',
            //提示语
            tipText:'',
            //刷新聊天状态赋值
            moni: '',
            x: '',
            //表情框默认隐藏
            expression:false,
            //对方用户信息
            toUserList:[],
            //对方头像id
            toUserAvatarId:'',
            //获取登录用户的头像id
            userAvatarId:'',
            //聊天框提示语
            chatText:'',

        }
    },
    created() {
        this.monitor()
    },
    mounted(){
        this.init()
    },
    //更新dom元素
    //让聊天室的滚动栏默认最下面
    updated (){
        this.$refs.box.scrollTop = this.$refs.box.scrollHeight
        // this.$refs.box.addEventListener('scroll', e => {
        //     console.log('滑动栏位置',this.$refs.box.scrollTop)
        //     this.x = this.$refs.box.scrollTop
        // })  
        // console.log('x',this.x)
        // if(this.x!=='' && this.x!==0){
        //     this.$nextTick(() => {
        //         this.$refs.box.scrollTo(0,this.x);
        //     })
        // }else{
        //     this.$refs.box.scrollTop = this.$refs.box.scrollHeight
        //     console.log('初始化距离',this.$refs.box.scrollTop)
        // }
    },
    methods: {
        //点击表情按钮显示表情框
        abc(){
            if(!this.expression){
                this.expression = true
            }else{
                this.expression = false
            }
        },
        //表情选择
        addEmoji(e) {
            var elInput = document.getElementById('emojiInput'); //根据id选择器选中对象
            var startPos = elInput.selectionStart;// input 第0个字符到选中的字符
            var endPos = elInput.selectionEnd;// 选中的字符到最后的字符
            if (startPos === undefined || endPos === undefined) return
            var txt = elInput.value;
            // 将表情添加到选中的光标位置
            var result = txt.substring(0, startPos) + e.native + txt.substring(endPos)
            elInput.value = result;// 赋值给input的value
            // 重新定义光标位置
            elInput.focus();
            elInput.selectionStart = startPos + e.native.length;
            elInput.selectionEnd = startPos + e.native.length;
            this.text  = result// 赋值给表单中的的字段
            this.expression=false
        },
        //刷新聊天状态
        liaotian () {
            //如果聊天对象不等于空
            if(this.chatUser!==''){
                if (this.moni !== null && this.moni !== '') {
                    this.chatUserName(this.moni)
                }
            }else{
                return
            }
            
        },
        //消息提示框
        message(message,type){
            this.$message({
                message:message,
                type: type
            });
        },
        //默认加载监听，判断是否输入账号
        monitor(){
            axios.get('http://127.0.0.1:8082/monitor/getmonitor').then(res=>{
                
            })
        },
        //查询聊天历史记录
        chatUserName(username){
            this.userAvatarId = window.sessionStorage.getItem("avatarId")
            this.moni = username
            if(this.chatUser===''){
                this.userName = window.sessionStorage.getItem("loginName")
                this.chatUser = username
                this.chatText =''
                axios.get('http://127.0.0.1:8082/chatRecord/getUserChatRecord' ,{
                    params:{
                        fromUserName: this.userName,
                        toUserName: this.chatUser
                    }
                }).then(res=>{
                    //获取自己和客服的聊天记录
                    this.chatRecordList = res.data.obj.record
                    //获取对方的头像id
                    this.toUserList = res.data.obj.avatarId
                    this.toUserList.forEach((item)=>{
                        this.toUserAvatarId = item.avatarId
                    })
                    //判断是自己的聊天内容还是客服的
                    this.chatRecordList.forEach((item)=>{
                        if(item.fromUsername === this.userName){
                            // 构建消息内容，本人消息
                            this.createContent(null, this.userName, item.chatContent,item.messageStatus)
                            this.text = ''
                        }
                        if(item.fromUsername === this.chatUser){
                            //构建消息内容，对方消息
                            this.createContent(this.chatUser,null,item.chatContent,item.messageStatus)
                            this.text = ''
                        }
                    })
                }).catch(error => {
                    this.$message.error('查询聊天记录失败！');
                })
            }else{
                this.userName = window.sessionStorage.getItem("loginName")
                //清空聊天区域
                this.content=''
                this.chatUser = username
                this.chatText =''
                //清空未读消息
                for(var i =0; i<this.users.length; i++){
                    if(this.users[i].username === this.chatUser){
                        if(this.users[i].unread && this.users[i].unread !==0){
                            this.users[i].unread = ''
                        }
                        else{
                            break
                        }
                    }
                }
                axios.get('http://127.0.0.1:8082/chatRecord/getUserChatRecord' ,{
                    params:{
                        fromUserName: this.userName,
                        toUserName: this.chatUser
                    }
                }).then(res=>{
                    this.content=''
                    //获取自己和客服的聊天记录
                    this.chatRecordList = res.data.obj.record
                    //获取对方的头像id
                    this.toUserList = res.data.obj.avatarId
                    this.toUserList.forEach((item)=>{
                        this.toUserAvatarId = item.avatarId
                    })
                    //判断是自己的聊天内容还是客服的
                    this.chatRecordList.forEach((item)=>{
                        if(item.fromUsername === this.userName){
                            // 构建消息内容，本人消息
                            this.createContent(null, this.userName, item.chatContent,item.messageStatus)
                            this.text = ''
                        }
                        if(item.fromUsername === this.chatUser){
                            //构建消息内容，对方消息
                            this.createContent(this.chatUser,null,item.chatContent,item.messageStatus)
                            this.text = ''
                        }
                    })
                }).catch(error => {
                    this.$message.error('查询聊天记录失败！');
                })
            }
        },
        //发送方法
        send() {
            this.userName = window.sessionStorage.getItem("loginName")
            if (!this.chatUser) {
                this.$message({type: 'warning', message: "请选择聊天对象"})
                return;
            }
            if (!this.text) {
                this.$message({type: 'warning', message: "请输入内容"})
            } else {
                if (typeof (WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                } else {
                    console.log("发送成功");
                    let message
                    // 组装待发送的消息 json
                    // {"from": "zhang", "to": "admin", "text": "聊天文本"}
                    if(this.userName==='qwe'){
                        message = {from: this.userName, to: this.chatUser, text: this.text, state: 1, time:new Date()}
                    }else{
                        message = {from: this.userName, to: this.chatUser, text: this.text, state: 0, time:new Date()}
                    }
                    socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
                    // 构建消息内容，本人消息
                    this.createContent(null, this.userName, this.text, message.state)
                    this.text = '';
                }
            }
        },
        //判断是自己发送的还是对方发送的内容
        createContent(remoteUser, nowUser, text, state) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
            let html
            let messageState
            if(state =='0'){
                messageState ='未读'
            }
            else{
                messageState ='已读'
            }
            // 当前用户消息
            if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
                html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
                    "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px;margin-top:16px;\">\n" +
                    "  <span style=\" text-align:right; font-size:12px; font-weight:bold;margin-right:20px;\">" + messageState + "</span>\n" +
                    "    <div class=\"tip left\">" + text + "</div>\n" +
                    "  </div>\n" +
                    "  <div class=\"el-col el-col-2\">\n" +
                    "  <span style=\" text-align:right; font-size:12px; font-weight:bold;margin-right:30px;\">我:" + this.userName + "</span>\n" +
                    "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
                    "    <img src=\"http://127.0.0.1:8082/getImageById?id="+this.userAvatarId+"\" style=\"object-fit: cover;\">\n" +
                    "  </span>\n" +
                    "  </div>\n" +
                    "</div>";
            } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡\
                html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
                    "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
                     "  <span style=\" text-align:left; font-size:12px; font-weight:bold;margin-left:20px;\">" + this.chatUser + "</span>\n" +
                    "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
                    "    <img src=\"http://127.0.0.1:8082/getImageById?id="+this.toUserAvatarId+"\" style=\"object-fit: cover;\">\n" +
                    "  </span>\n" +
                    "  </div>\n" +
                    "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px; margin-top:16px;\">\n" +
                    "    <div class=\"tip right\">" + text + "</div>\n" +
                    "  </div>\n" +
                    "</div>";
            }
            this.content += html;
        },
        //开启webstocket会话
        init() {
            if(window.sessionStorage.getItem("loginName")===null){
                return
            }
            let username
            username = window.sessionStorage.getItem("loginName");
            let _this = this;
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");
                //创建一个websocket连接
                let socketUrl = "ws://localhost:8082/imserver/" + username;
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                // 开启一个websocket服务
                socket = new WebSocket(socketUrl);
                //打开事件onopen
                //发送至后端
                socket.onopen = function () {
                    console.log("websocket已打开");
                };
                // 浏览器端收消息，获得从服务端发送过来的文本消息
                socket.onmessage = function (msg) {
                    // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
                    let data = JSON.parse(msg.data)
                    // 获取在线人员信息
                    if (data.users) {  
                        // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
                        //如果是客服账号就直接显示所有在线的用户
                        if(username==='qwe'){
                            _this.users = data.users.filter(user => user.username !== username)
                            if(_this.chatUser===''){
                                    _this.chatText ="请在左侧栏中选择聊天对象"
                            }
                            if(_this.users.length>0){
                                _this.tipText ="在线用户（点击气泡开始聊天）"
                            }else{
                                _this.tipText ="当前没有用户"
                                //清空聊天对象
                                _this.chatUser= ''
                                if(_this.chatUser===''){
                                    _this.chatText ="请在左侧栏中选择聊天对象"
                                }
                            }  
                        }
                        //如果是用户账号则只显示客服账号
                        else{
                            _this.users = data.users.filter(user => user.username ==='qwe')
                            if(_this.chatUser===''){
                                    _this.chatText ="请在左侧栏中选择聊天对象"
                            }
                                if(_this.users.length ===0){
                                    _this.tipText ="当前客服未在线"
                                    //清空聊天对象
                                    _this.chatUser= ''
                                    if(_this.chatUser===''){
                                        _this.chatText ="请在左侧栏中选择聊天对象"
                                    }
                                }else{
                                    _this.tipText ="在线客服（点击气泡开始聊天）"
                                }  
                        }
                        // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
                        //  // {"from": "zhang", "text": "hello"}  
                    } else {
                        //当用户和客服选中的聊天的用户一致时
                        //说明客服已经选中该用户，该用户发的所有消息状态转为已读
                        if (data.from === _this.chatUser) {
                            //将消息状态转为1即已读
                            data.state ='1'
                            //当有人给客服发消息的时
                            //这个聊天记录的数组不为空
                            if(_this.ThatMessages.length>0){
                                //循环这个数组
                                for(var i =0; i<_this.ThatMessages.length; i++){
                                    //判断这里有没有当前用户发送给客服的消息，有就把它输出出来并把该聊天内容移出出未读数组里
                                    if(_this.ThatMessages[i].from===_this.chatUser){
                                        //构建消息内容，对方消息
                                        _this.ThatMessages[i].state = 1
                                        _this.createContent(data.from, null, _this.ThatMessages[i].text, _this.ThatMessages[i].state)
                                        _this.ThatMessages.splice(i,1)
                                        i--
                                        if(_this.ThatMessages.length===0){
                                            break
                                        }
                                    }else{
                                        break
                                    }
                                }
                                //如果当前用户没有发送消息，则直接输出消息内容
                                console.log("未读消息里没有该用户发送的信息")
                                 //构建消息内容，对方消息
                                _this.createContent(data.from, null, data.text, data.state)
                            }
                            //如果未读的聊天数组为0则直接输出消息内容
                            if(_this.ThatMessages.length===0){
                                // 构建消息内容
                                _this.createContent(data.from, null, data.text, data.state)
                            }
                        }
                        //如果客服在跟别的用户聊天但当前用户给客服发消息时，就将该聊天记录存放进一个数组
                        //再给客服的列表中显示未读消息的条数
                        if (data.from!==_this.chatUser){
                            _this.ThatMessages.push(data)
                            _this.users.forEach((item)=>{
                                if(item.username === data.from){
                                    if(item.unread){
                                        item.unread += 1
                                    }else{
                                        item.unread = 1
                                    }
                                    
                                }
                            })
                        }
                    }
                };
                //关闭事件
                socket.onclose = function () {
                    console.log("websocket已关闭");
                }
                //发生了错误事件
                socket.onerror = function () {
                    console.log("websocket发生了错误");
                }
            }
        }
    }
}
</script>
<style>
.chat_div{
    margin: 0 auto;
    width:1200px;
    height:800px;
}
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}

.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
.emoji-mart[data-v-7bc71df8] {
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-direction: column;
  flex-direction: column;
  height: 420px;
  color: #ffffff !important;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  background: #fff;
}
</style>
